package com.zhongyu.item.consumer.elastic;

import com.zhongyu.comm.api.ImageApi;
import com.zhongyu.comm.api.ItemApi;
import com.zhongyu.comm.pojo.Item;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 同步dm_item表中的内容到ES
 */
@Component
public class SyncItemToEs {

    @Resource
    private ItemApi itemApi;

    @Resource
    private ImageApi imageApi;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Scheduled(initialDelay = 3000,fixedDelay = 100000)
    public void transferDataToEs(){
       ValueOperations<String,Object>  valueOperations=redisTemplate.opsForValue();
       LocalDateTime syncTime= (LocalDateTime) valueOperations.get("sync:time");
        List<Item> list=null;
       if(syncTime==null){

          list=  itemApi.findAll();
       }else{
           list=itemApi.findBySyncTime(syncTime);
       }
       valueOperations.set("sync:time",LocalDateTime.now());
       if(list!=null&&list.size()>0){
           elasticsearchRestTemplate.save(list);
       }
    }


}
